import Store from '../store'
import Interact from './interact'

export function timestampToCountdown(timestamp, formatStr = "hh:mm:ss", formatAdditional) {
	const timestampNum = parseInt(timestamp);
	const rule = {
		"d+": Math.floor(timestampNum / 1000 / 60 / 60 / 24), // 日
		"h+": Math.floor(timestampNum / 1000 / 60 / 60 % 24), // 时
		"m+": Math.floor(timestampNum / 1000 / 60 % 60), // 分
		"s+": Math.floor(timestampNum / 1000 % 60), // 秒
		"S": Math.floor(timestampNum % 1000) // 毫秒
	};

	let formatRes = rule["d+"] > 0 ? formatAdditional + formatStr : formatStr;

	for (let analytical in rule) {
		if (new RegExp("(" + analytical + ")").test(formatRes)) {
			formatRes = formatRes.replace(RegExp.$1, RegExp.$1.length === 1 ? rule[analytical] : ("00" + rule[
				analytical]).substr(("" + rule[analytical]).length));
		}
	}

	return formatRes;
}
// time '2020-12-12 12:12:12'
export function timestampToLocalDayPlus(time) {
	let result = '';
	let now = new Date().getTime();
	let diffValue = now - new Date(Date.parse(time.replace(/-/g, "/")))
	if (diffValue < 0) {
		result = "刚刚"
	} else {
		let minute = 1000 * 60;
		let hour = minute * 60;
		let day = hour * 24;
		let dayC = diffValue / day;
		let hourC = diffValue / hour;
		let minC = diffValue / minute;
		if (parseInt(dayC) > 2) {
			result = time
		} else if (parseInt(dayC) >= 1) {
			result = "" + parseInt(dayC) + "天前";
		} else if (hourC >= 1) {
			result = "" + parseInt(hourC) + "小时前";
		} else if (minC >= 1) {
			result = "" + parseInt(minC) + "分钟前";
		} else {
			result = "刚刚";
		}
	}
	return result;
}
export const randomString = () => {
	let len = 32
	// let $chars = 'ABCDEFGHJKMNOPQRSTUVWXYZabcdefghijkmnprstwxyz123456789'
	let $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
	let maxPos = $chars.length
	let pwd = ''
	for (let i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
	}
	return pwd
}

export const getLocation = () => {
	return new Promise(async (resolve, reject) => {
		const uniApiToPromise = (api, params) => {
			return new Promise((reso, reje) => {
				uni[api]({
					...params,
					success(res) {
						if (typeof res.latitude != 'undefined') {
							reso(res)
						}
					},
					fail(err) {
						reje(err)
					}
				})
			})
		}
		let location;
		try {
			location = await uniApiToPromise('getLocation', {
				type: 'gcj02'
			})
			resolve(location)
		} catch (err) {
			console.log('gggggggggg', err);
			uni.showModal({
				title: '位置',
				content: '无位置信息，不能提供精确服务，请允许获取您当前位置',
				success: res => {
					if (res.confirm) {
						uni.openSetting({
							async success() {
								let auth = await uniApiToPromise('getSetting')
								if (auth.authSetting['scope.userLocation']) {
									location = await uniApiToPromise(
										'getLocation', {
											type: 'gcj02'
										})
									resolve(location)
								} else {
									reject()
								}
							},
							fail(err) {
								console.log(err);
							}
						})
					} else {
						reject()
					}
				}
			})
		}
	})

}

export function throttle(fn, delay = 200) {
	let canRun = true;
	return function() {
		if (!canRun) return;
		fn.apply(this, arguments);
		canRun = false;
		setTimeout(() => {
			canRun = true;
		}, delay);
	};
}


export function debounce(fn, delay = 200) {
	let timer = null;
	return function() {
		clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(this, arguments)
			timer = null
		}, delay)
	}
}


export function downloadFile(onlineFilePath) {
	return new Promise((resolve, reject) => {
		// 新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
		uni.showLoading({
            mask: true,
			title: "正在打开···"
		})
		uni.downloadFile({
			url: onlineFilePath,
			fail: (err) => {
				console.log(err);
				Interact.toast('文件下载失败')
			},
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						fail: (err) => {
							console.log(err);
							Interact.toast('文件保存失败')
						},
						success: function(data) {
							setTimeout(() => {
								uni.openDocument({
									filePath: data.savedFilePath,
									showMenu: true,
									fail: (err) => {
										console.log(err);
										Interact.toast('文件打开失败')
									},
									success: function() {
										resolve()
										uni.hideLoading()
									}
								})
							}, 3000);
						}
					})

				}
			}
		});
	})

}

export function downloadImage(onlineFilePath) {
	return new Promise((resolve, reject) => {
		// 新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
		uni.showLoading({
            mask: true,
			title: "正在下载···"
		})
		uni.downloadFile({
			url: onlineFilePath, //图片的地址
			success: function(res) {
				const tempFilePath = res.tempFilePath //通过res中的tempFilePath 得到需要下载的图片地址
				uni.saveImageToPhotosAlbum({
					filePath: tempFilePath, //设置下载图片的地址
					success: function() {
						Interact.toast('下载成功')
					},
					fail: (err) => {
						console.log(err);
						Interact.toast('下载失败')
					},
				})
			},
			fail: (err) => {
				console.log(err);
				Interact.toast('下载失败')
			},
		})
	})

}
